<template>
  <div class="oragnization" curPageName="orgstreecomp123456789">
    <div class="search_input">
      <el-input v-model="filterText" :suffix-icon="Search" placeholder="输入关键字进行过滤" clearable />
    </div>
    <el-scrollbar ref="scrollBarRef" :style="{ height: `calc(100% - 56px)` }">
      <!--default-expand-all -->
      <el-tree
        v-if="reloadBool"
        ref="treeRef"
        class="filter-tree"
        highlight-current
        :props="defaultProps"
        :expand-on-click-node="false"
        icon-class="none"
        :data="treeData"
        auto-expand-parent
        :default-expanded-keys="defaultExpKeys"
        :node-key="defauleKey"
        :current-node-key="defaultKey"
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data }">
          <span class="el-tree-node__label"> {{ node.label }}</span>
        </template>
      </el-tree>
    </el-scrollbar>
  </div>
</template>
<script setup lang="ts">
import { ref, watch, watchEffect, onMounted, nextTick, defineProps, withDefaults, defineExpose } from "vue";
import type { ElTree } from "element-plus";
import { useOraStore } from "@/stores/modules/oragnization";
import { getOrganizationTreeApi } from "@/api/modules/public";

import { Search } from "@element-plus/icons-vue";

const oraStore = useOraStore();

// 设置默认key
let reloadBool = ref(true);
let defauleKey = ref("mix_id");
let defaultExpKeys = ref([]);
// 使用 withDefaults 设置默认值
const props = withDefaults(
  defineProps<{
    defTreeValue?: Number; //当前值
    parentTreeValue?: Number; //部门ID
    treeLevel?: Number; //需要数据级别
  }>(),
  {
    defTreeValue: () => 0,
    treeLevel: () => 2 // 设置默认值
  }
);
interface Tree {
  [key: string]: any;
}

const filterText = ref("");
const scrollBarRef = ref();

const treeRef = ref<InstanceType<typeof ElTree>>();

let defaultKey = ref(""); //树结构默认选中值

// 当props发生改变时会触发这里的逻辑
watchEffect(() => {
  //  props.defTreeValue     props.parentTreeValue
  defaultKey.value = Number(props.defTreeValue) || 0;
  if (props.parentTreeValue && props.treeLevel == 3) {
    //如果父级参数有值1_8
    defaultKey.value = `${Number(props.parentTreeValue)}_${Number(props.defTreeValue)}`;
  }
});

watch(filterText, val => {
  treeRef.value!.filter(val);
});

const defaultProps = {
  children: "children",
  label: "title",
  isLeaf: (data, node) => {
    if (node.childNodes.length) {
      return true;
    }
  }
};

const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.title.includes(value);
};
//#region 初始化接口
const treeData: Tree[] = ref<InstanceType<typeof ElTree>>();
const initTree = () => {
  if (props.treeLevel == 3) {
    defauleKey.value = "mix_id";
    let treeAll = oraStore.oragnizationTreeAll;
    treeAll[0].mix_id = "0_0";
    treeData.value = treeAll;
  }
  if (props.treeLevel == 2) {
    defauleKey.value = "org_id";
    treeData.value = oraStore.oragnizationTreeTwo;
  }

  if (props.treeLevel == 1) {
    defauleKey.value = "org_id";
    treeData.value = oraStore.oragnizationTreeOne;
  }

  reloadBool.value = false;
  nextTick(() => {
    reloadBool.value = true;
    treeRef.value?.setCheckedKeys(defaultKey.value);

    //树结构滚动到默认位置
    setTimeout(() => {
      // treeRef.value?.getNode(node).parent.data;
      let node = treeRef.value?.getCurrentNode();

      if (props.treeLevel == 3) {
        defaultExpKeys.value = [node?.mix_id];
      } else {
        defaultExpKeys.value = [node.parent_id];
      }

      getTreeTop();
    });
  });
};
//获取当前选中节点数据
const getTreeTop = () => {
  let nodeKey = document.querySelector(".el-tree-node .is-current");
  let nodesArr = document.getElementsByClassName("el-tree-node");

  if (nodesArr[nodesArr.length - 1] == document.getElementsByClassName("el-tree-node is-current")[0]) {
    //最后一个直接滚动到底有问题，先获取到上一个在滚动
    nodeKey = nodesArr[nodesArr.length - 2];
  }
  if (nodeKey) nodeKey.scrollIntoView({ block: "center" });
};

//#endregion

onMounted(() => {
  //
  initTree();
});

// emit
const emit = defineEmits<{
  change: [value: any];
}>();

const handleNodeClick = data => {
  let { parent_id, org_id, level } = data;
  let paramsObj = {
    parent_id: parent_id,
    org_id: org_id,
    level: level
  };
  emit("node-change", paramsObj);
};

// 暴露给父组件使用
defineExpose({ treeRef, scrollBarRef });
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
